package com.eastfair.pay.service.impl;

import com.eastfair.pay.dao.StatisticsMapper;
import com.eastfair.pay.service.StatisticsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 交易统计
 *
 * @author Du Xiaobo
 * @date 2023/6/21 15:03
 */
@Slf4j
@Service
public class StatisticsServiceImpl implements StatisticsService {

    private final static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
    private final static SimpleDateFormat format_day = new SimpleDateFormat("yyyy-MM-dd");

    @Resource
    private StatisticsMapper baseMapper;

    @Override
    public Map<String, Object> orderStatusStatistics(String startTime, String endTime, String orderType) {

        List<Map<String, Object>> mapList = baseMapper.orderStatusStatistics(startTime, endTime, orderType);
        Map<String, Object> map = new HashMap<>(mapList.size());
        mapList.forEach(m -> map.put(m.get("order_status").toString(), m.get("amount")));
        return map;
    }

    @Override
    public Map<String, Object> orderTypeStatistics(String startTime, String endTime, String orderType) {
        Map<String, Object> map = new HashMap<>(2);
        List<Map<String, Object>> list = baseMapper.orderTypeStatistics(startTime, endTime, orderType);
        List<Object> days = list.stream().map(l -> l.get("days")).collect(Collectors.toList());
        List<Object> amounts = list.stream().map(l -> l.get("amount")).collect(Collectors.toList());
        map.put("days", days);
        map.put("amounts", amounts);
        return map;
    }

    @Override
    public Map<String, Object> revenueAndExpenditureStatistics(String month, String payee) {

        Map<String, Object> map = new HashMap<>();

        Date date = new Date();
        try {
            date = format.parse(month);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String startDate = getMonthStartDay(date);
        String endDate = getMonthEndDay(date);

        String previousEndDate = getMonthEndDay(getPreviousDate(date));

        // 查询收入
        Double revenue = baseMapper.revenue(startDate, endDate, payee);
        Integer revenueCount = baseMapper.revenueCount(startDate, endDate, payee);
        // 查询支出
        Double expenditure = baseMapper.expenditure(startDate, endDate, payee);
        Integer expenditureCount = baseMapper.expenditureCount(startDate, endDate, payee);
        // 查询期初余额
        Double startBalance = baseMapper.balance(previousEndDate, payee);
        // 查询期末余额
        Double endBalance = baseMapper.balance(endDate, payee);
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        // 收入
        map.put("revenue", decimalFormat.format(revenue));
        // 收入条数
        map.put("revenueCount", revenueCount);
        // 支出条数
        map.put("expenditureCount", expenditureCount);
        // 支出
        map.put("expenditure", decimalFormat.format(expenditure));
        // 期初余额
        map.put("startBalance", decimalFormat.format(startBalance));
        // 期末余额
        map.put("endBalance", decimalFormat.format(endBalance));

        return map;
    }


    @Override
    public Map<String, Object> revenueAndExpenditureLineStatistics(String month, String payee, Integer type) {
        log.info("入参：month={}，payee={}，type={}", month, payee, type);
        Map<String, Object> map = new HashMap(2);
        List<Object> days;
        List<Object> amounts;
        Date date = new Date();
        try {
            synchronized (this) {
                date = format.parse(month);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String startDate = getMonthStartDay(date);
        String endDate = getMonthEndDay(date);

        if (type.equals(0)) {
            // 收入
            List<Map<String, Object>> list = baseMapper.revenueLine(startDate, endDate, payee);
            days = list.stream().map(l -> l.get("days")).collect(Collectors.toList());
            amounts = list.stream().map(l -> l.get("amount")).collect(Collectors.toList());
        } else {
            // 支出
            List<Map<String, Object>> list = baseMapper.expenditureLine(startDate, endDate, payee);
            days = list.stream().map(l -> l.get("days")).collect(Collectors.toList());
            amounts = list.stream().map(l -> l.get("amount")).collect(Collectors.toList());
        }
        map.put("days", days);
        map.put("amounts", amounts);
        return map;
    }


    /**
     * 获取指定时间月的第一天
     *
     * @param date
     * @return
     */
    private synchronized String getMonthStartDay(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        //设置为1号,当前日期既为本月第一天
        cal.set(Calendar.DAY_OF_MONTH, 1);
        return format_day.format(cal.getTime());
    }

    /**
     * 获取指定时间月的最后一天
     *
     * @param date
     * @return
     */
    private synchronized String getMonthEndDay(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        return format_day.format(cal.getTime());
    }

    /**
     * 获取上个月的日期
     *
     * @param date
     * @return
     */
    private Date getPreviousDate(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, -1);
        return cal.getTime();
    }
}
